 package com.itic.mobile.product;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.itic.appbase.applications.sys.user.persistence.model.SysUser;
import com.itic.appbase.framework.common.constants.DBConst;
import com.itic.appbase.framework.utils.StringHelper;
import com.itic.appbase.framework.utils.ValueHelper;
import com.itic.mobile.base.BaseMobile;
import com.itic.system.market.category.persistence.model.Category;
import com.itic.system.market.category.persistence.model.CategoryExample;
import com.itic.system.market.category.service.CategoryService;
import com.itic.system.market.product.persistence.model.Product;
import com.itic.system.market.productitem.persistence.model.ProductItem;
import com.itic.system.market.productitem.service.ProductItemService;

@Controller
@RequestMapping(value = "/mobile/product")
public class ProductMobile extends BaseMobile {
	@Autowired
	private CategoryService categoryService;
	@Autowired
	private ProductItemService productItemService;
	
	private static String VIP="vip";

	// 商品过滤字段
	protected static String[] ignoreCategoryProperties = new String[] { "id", "createUser", "isEffective", "updateTime",
			"note", "createTime", "orgCode", "reorder", "parentId" };

	// 商品过滤字段
	protected static String[] ignoreProductProperties = new String[] { "id", "createUser", "isEffective", "updateTime",
			"note", "createTime", "orgCode", "reorder", "parentId" };

	// 商品过滤字段
	protected static String[] ignoreProductItemProperties = new String[] {  "createUser", "isEffective",
			"updateTime", "note", "createTime", "orgCode", "reorder", "productId","fee","isVipVideo","videoUrl" };

	/**
	 * 商品列表
	 * 
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "/categorys")
	@ResponseBody
	public Map<String, Object> categorys(HttpServletRequest request, HttpServletResponse response) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		String errorCode = PARAM_ERROR_CODE;
		String errorMsg = PARAM_ERROR_MSG;
		try {
			Map<String, Object> dataMap = new HashMap<String, Object>();

			CategoryExample example = new CategoryExample();
			example.setOrderByClause("REORDER ASC");
			com.itic.system.market.category.persistence.model.CategoryExample.Criteria criteria = example
					.createCriteria();
			criteria.andIsEffectiveEqualTo(DBConst.TRUE);// 是否有效
			this.handlePageQueryDefault(request, example);// 分页
			int count = categoryService.count(example);// 总条数
			List<Category> list = categoryService.list(example);// 数据list

			dataMap.put("total", count);
			dataMap.put("isMore", isMore(request, count));

			dataMap.put("list", ValueHelper.tranList2MapList(list, ignoreCategoryProperties));
			resultMap.put(DATA, dataMap);
			errorCode = SUCCESS_ERROR_CODE;
			errorMsg = SUCCESS_ERROR_MSG;
		} catch (Exception e) {
			e.printStackTrace();
			errorCode = SERVER_ERROR_CODE;
			errorMsg = SERVER_ERROR_MSG;
			logException("ProductMobile", "categorys", e.toString(), "商品分类列表信息", e);
		}
		resultMap.put(CODE, errorCode);
		resultMap.put(MSG, errorMsg);
		isCrrossDomain(response);
		return resultMap;
	}
	
	
	

	/**
	 * 商品列表
	 * 
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "/list")
	@ResponseBody
	public Map<String, Object> list(HttpServletRequest request, HttpServletResponse response, String categoryCode,
			String keyword) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		String errorCode = PARAM_ERROR_CODE;
		String errorMsg = PARAM_ERROR_MSG;
		try {
			resultMap.put(DATA, getProductList(request, categoryCode, keyword));
			errorCode = SUCCESS_ERROR_CODE;
			errorMsg = SUCCESS_ERROR_MSG;
		} catch (Exception e) {
			e.printStackTrace();
			errorCode = SERVER_ERROR_CODE;
			errorMsg = SERVER_ERROR_MSG;
			logException("ProductMobile", "list", e.toString(), "商品列表", e);
		}
		resultMap.put(CODE, errorCode);
		resultMap.put(MSG, errorMsg);
		isCrrossDomain(response);
		return resultMap;
	}

	/**
	 * 商品详情
	 * 
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "/detail")
	@ResponseBody
	public Map<String, Object> detail(HttpServletRequest request, HttpServletResponse response, String productId,String token,String device) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		String errorCode = PARAM_ERROR_CODE;
		String errorMsg = PARAM_ERROR_MSG;
		try {
			if (StringHelper.isNotBlank(productId)) {
				Product product = productService.get(productId);
				if (null != product) {
					Map<String, Object> dataMap = new HashMap<String, Object>();
					SysUser user = sysUserService.getUserByTokenAndDevice(token, device);
					List<ProductItem> list = productService.getProductItems(product);
					
					String videlUrl="";
					Double fee = 0.00;//默认费用为0
					String isCollect = "noCollected";//默认未收藏
					String preImage = product.getProductImage();
					String productName = product.getProductName();
					Integer playCounts = product.getPlayCounts();
					String summary = product.getSummary();
					String isBuy = "nobuy";
					if( !list.isEmpty() ){
						ProductItem productItem = list.get(0);
						fee = productItem.getFee();
						preImage = productItem.getImage();
						summary = productItem.getSummary();
						//如果当前视频是收费视频的话
						if( productItem.getFee() > 0 && productItem.getIsVipVideo().equals(VIP) ){
							//判断用户是否购买了当前视频 
							if( null != user ){
								isCollect = productService.isCollectByUser(user,product);
								//判断用户是否为会员
								if( VIP.equals(productItem.getIsVipVideo()) && VIP.equals(user.getIsVip()) ){
									isBuy = "buyed";
									videlUrl=productItem.getVideoUrl();
									//添加播放次数
									productService.addPlayCounts(product);
								}
								//判断用户是否已购买此视频
								if( productService.isBuyProductItem(user,productItem) ){
									isBuy = "buyed";
									videlUrl=productItem.getVideoUrl();
									//添加播放次数
									productService.addPlayCounts(product);
								}
							}
						}else{
							videlUrl=productItem.getVideoUrl();
							isBuy = "buyed";
							//添加播放次数
							productService.addPlayCounts(product);
						}
						videlUrl=productItem.getVideoUrl();
					}
					dataMap.put("productName", productName);
					dataMap.put("playCounts", playCounts);
					dataMap.put("isBuy", isBuy);
					dataMap.put("videoUrl", videlUrl);
					dataMap.put("fee", fee);
					dataMap.put("isCollect", isCollect );
					dataMap.put("preImage", preImage);
					dataMap.put("summary", summary);
					dataMap.put("isBuy", isBuy);
					dataMap.put("items", ValueHelper.tranList2MapList(list, ignoreProductItemProperties));
					resultMap.put(DATA, dataMap);
					errorCode = SUCCESS_ERROR_CODE;
					errorMsg = SUCCESS_ERROR_MSG;
				} else {
					errorCode = PRODUCT_EMPTY_ERROR_CODE;
					errorMsg = PRODUCT_EMPTY_ERROR_MSG;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			errorCode = SERVER_ERROR_CODE;
			errorMsg = SERVER_ERROR_MSG;
			logException("ProductMobile", "detail", e.toString(), "商品详情", e);
		}
		resultMap.put(CODE, errorCode);
		resultMap.put(MSG, errorMsg);
		isCrrossDomain(response);
		return resultMap;
	}
	
	
	/**
	 * 商品项详情
	 * 
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "/detailItem")
	@ResponseBody
	public Map<String, Object> detailItem(HttpServletRequest request, HttpServletResponse response, String itemId,String token,String device) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		String errorCode = PARAM_ERROR_CODE;
		String errorMsg = PARAM_ERROR_MSG;
		try {
			if (StringHelper.isNotBlank(itemId)) {
				ProductItem productItem = productItemService.get(itemId);
				if (null != productItem) {
					Map<String, Object> dataMap = new HashMap<String, Object>();
					SysUser user = sysUserService.getUserByTokenAndDevice(token, device);
					
					Double fee = productItem.getFee();
					String preImage = productItem.getImage();
					String videoUrl = "";
					String isBuy = "nobuy";
					//如果当前视频是收费视频的话
					if( productItem.getFee() > 0 ){
						//判断用户是否购买了当前视频 
						if( null != user ){
							//判断用户是否为会员
							if( VIP.equals(productItem.getIsVipVideo()) && VIP.equals(user.getIsVip()) ){
								isBuy = "buyed";
								videoUrl=productItem.getVideoUrl();
								//添加播放次数
								productService.addPlayCounts(productItem);
							}
							//判断用户是否已购买此视频
							if( productService.isBuyProductItem(user,productItem) ){
								isBuy = "buyed";
								videoUrl=productItem.getVideoUrl();
								//添加播放次数
								productService.addPlayCounts(productItem);
							}
						}
					}else{
						isBuy = "buyed";
						videoUrl=productItem.getVideoUrl();
						//添加播放次数
						productService.addPlayCounts(productItem);
					}
					videoUrl=productItem.getVideoUrl();
					dataMap.put("videoUrl", videoUrl);
					dataMap.put("fee", fee);
					dataMap.put("preImage", preImage);
					dataMap.put("summary", productItem.getSummary());
					dataMap.put("isBuy", isBuy);
					resultMap.put(DATA, dataMap);
					errorCode = SUCCESS_ERROR_CODE;
					errorMsg = SUCCESS_ERROR_MSG;
				} else {
					errorCode = PRODUCT_EMPTY_ERROR_CODE;
					errorMsg = PRODUCT_EMPTY_ERROR_MSG;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			errorCode = SERVER_ERROR_CODE;
			errorMsg = SERVER_ERROR_MSG;
			logException("ProductMobile", "detailItem", e.toString(), "商品项详情", e);
		}
		resultMap.put(CODE, errorCode);
		resultMap.put(MSG, errorMsg);
		isCrrossDomain(response);
		return resultMap;
	} 
}